﻿using System;
using System.Data;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using Besture.Bll;
using Besture.Common;
using Besture.Common.Helper;
using Besture.Model;

namespace Besture.UI
{
    public partial class RoomPriceList : BasePage
    {
        public DateTime IDataNow = DateTime.Now;

        #region 页面加载事件

        /// <summary>
        ///     页面加载
        /// </summary>
        protected override void InitialLoad()
        {
            //页面加载
            InitPage();
            calendarWrap.Visible = false;
        }

        /// <summary>
        ///     回发
        /// </summary>
        protected override void PostBackLoad()
        {
            InitPage();
        }

        /// <summary>
        ///     页面加载
        /// </summary>
        public void InitPage()
        {
            //早餐情况 绑定
            DataTable vBreakfast = QueryDac.GetTable("SELECT * FROM TBDictionaryType WHERE Type = 5");
            BindDropDownList(ddl_box_Breakfast, vBreakfast, "name", "code");
        }

        private static void BindDropDownList(DropDownList dropDownList, DataTable sourceTable, string dataTextField,
            string dataValueField)
        {
            if (sourceTable != null)
            {
                dropDownList.DataSource = sourceTable;
                dropDownList.DataTextField = dataTextField;
                dropDownList.DataValueField = dataValueField;
                dropDownList.DataBind();
            }
        }

        #endregion

        /// <summary>
        ///     日历html
        /// </summary>
        /// <param name="roomId">房型id</param>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public string GetCalendarData(int roomId)
        {
            string tableHtml;
            string sdata = Convert.ToString(IDataNow.Year + "-" + IDataNow.Month);
            int days = Thread.CurrentThread.CurrentUICulture.Calendar.GetDaysInMonth(IDataNow.Year, IDataNow.Month);
            string sHtml = string.Empty;
            for (int i = 1; i <= days; i++)
            {
                //第一行合并表格
                if (i == 1)
                {
                    if (GetWeek(Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month + "-01")) != "7")
                    {
                        sHtml += string.Format("<td colspan={0} class='disabled'></td>",
                            GetWeek(Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month + "-01")));
                    }
                }

                /**
                 * 1.判断是否房间开放 
                 * 2.是否房间关闭
                 * 3.是否限量售卖
                 * 4.是否无房价/不可订
                 * 5.是否大床满 
                 * 6.是否双床满 
                 */

                //1.日历 显示会员价格 并 显示 早餐情况

                //1.判断是否房间开放 
                DateTime data = Convert.ToDateTime(sdata + '-' + i);
                string sdisabled = string.Empty;
                string vdining = "ico-dining1"; //早餐图片默认高亮显示
                if (data.Date < DateTime.Now.Date)
                {
                    sdisabled = "disabled";
                    vdining = "ico-dining";
                }

                //2.显示会员价格
                RoomPriceModel vPriceModel = new RoomPriceDac().GetModelByRoomIdAndRoomTime(roomId, data);
                string sLowPrice = string.Empty;
                int vBreakfast = 0;

                if (vPriceModel != null)
                { 
                    sLowPrice = Convert.ToString(vPriceModel.LowPrice); //低价
                    vBreakfast = vPriceModel.Breakfast; //显示早餐信息
                }

                //生成td 
                sHtml += string.Format("<td class='{0}' tabindex='{6}' date='{1}'><div>" +
                                       "<ul class='price-list'> " +
                                       " <li class='li-date'>{2}</li>" +
                                       " <li class='li-roomCount'>{3}</li>" +
                                       " <li class='{4}'><i></i>{5}</li>" +
                                       "</ul>" +
                                       "</div></td>", sdisabled, (sdata + '-' + i), i, sLowPrice, vdining, vBreakfast, sLowPrice);

                //处理 7天单位 换行
                string weekstr = GetWeek(Convert.ToDateTime(sdata + "-" + i));
                if (weekstr.Equals("6"))
                {
                    //生成td 换行   
                    sHtml = string.Format("<tr>{0}</tr>", sHtml);
                }
            }

            DateTime date = Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month).AddMonths(1).AddDays(-1);
            if (GetWeek(date) != "6")
                tableHtml = sHtml +
                            string.Format("<td colspan='{0}' class='disabled'></td>",
                                7 - Convert.ToInt32(GetWeek(date) == "7" ? "1" : GetWeek(date)));
            else
                tableHtml = sHtml;

            return tableHtml;
        }

        private string GetWeek(DateTime data)
        {
            string weekstr = data.DayOfWeek.ToString();
            switch (weekstr)
            {
                case "Monday":
                    weekstr = "1";
                    break;
                case "Tuesday":
                    weekstr = "2";
                    break;
                case "Wednesday":
                    weekstr = "3";
                    break;
                case "Thursday":
                    weekstr = "4";
                    break;
                case "Friday":
                    weekstr = "5";
                    break;
                case "Saturday":
                    weekstr = "6";
                    break;
                case "Sunday":
                    weekstr = "7";
                    break;
            }
            return weekstr;
        }


        /// <summary>
        ///     查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSeachClick(object sender, EventArgs e)
        {
            GetSeach();
        }

        private void GetSeach()
        { 
            var dt = new DataTable();
            string[] sId = hidID.Value.Split('|');

            //0表示显示酒店全部房型 反之1某一个房型
            dt = sId[0] == "0"
                ? new RoomDac().GetRoomByIDorHotelsId(0, Convert.ToInt32(sId[1]))
                : new RoomDac().GetRoomByIDorHotelsId(Convert.ToInt32(sId[1]), 0);

            string month = hidColendarMonth.Value;
            switch (month)
            {
                case "1":
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + (Convert.ToInt32(txtMonth.Value) - 1));
                    // 1表示前月份  
                    txtMonth.Value = (Convert.ToInt32(txtMonth.Value) - 1).ToString();
                    break;
                case "2":
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + (Convert.ToInt32(txtMonth.Value) + 1));
                    //2表示后月份  
                    txtMonth.Value = (Convert.ToInt32(txtMonth.Value) + 1).ToString();
                    break;
                case "3":
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + Convert.ToInt32(txtMonth.Value));
                    //3表示当前页面
                    txtMonth.Value = (Convert.ToInt32(txtMonth.Value)).ToString();
                    break;
                default:
                    IDataNow = Convert.ToDateTime(IDataNow.Year + "-" + IDataNow.Month); //默认当月份
                    txtMonth.Value = (IDataNow.Month).ToString();
                    break;
            }


            if (dt.Rows.Count > 0)
                calendarWrap.Visible = true;

            rpRoom.DataSource = dt;
            rpRoom.DataBind();

            //绑定数据后重新注册一下JS事件
            GetRegister();
        }

        /// <summary>
        ///     绑定数据后重新注册一下JS事件
        /// </summary>
        private void GetRegister()
        {
            //绑定数据后重新注册一下JS事件
            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel2, GetType(), "Hotels",
                "GetInLoadCalendar();setTab(this,0);GetQuery();getUpdateHotels();getBtnBlue();", true);
        }


        //处理价格事件
        protected void btnSavePrice_Click(object sender, EventArgs e)
        {
            try
            {
                hidColendarMonth.Value = "3";
                var dac = new RoomPriceDac();
                var model = new RoomPriceModel();
                var baseDac = new BaseDac<RoomPriceModel>();
                int lsRecord = 0;
                string[] sRoomId = hidRoom.Value.Split('|');
                if (sRoomId.Length > 0)
                {
                    model.RoomID = Convert.ToInt32(sRoomId[0]);
                    model.LowPrice = Convert.ToDecimal(txt_box_LowPrice.Value);
                    model.IsDeleted = 0;
                    model.Breakfast = hidBreakfast.Value != "" ? Convert.ToInt32(hidBreakfast.Value) : 0;
                    baseDac.LoadAddBaseModel(model);
                    string[] sRoomTime = sRoomId[1].TrimEnd(',').Split(',');
                    foreach (string t in sRoomTime)
                    {
                        model.RoomTime = Convert.ToDateTime(t);
                        model.SortID = Convert.ToInt32(SortService.GetSortID("TBRoomPrice", false));
                        //lsRecord = dac.Add(model);
                        lsRecord =
                            new RoomPriceDac().GetModelByRoomIdAndRoomTime(model.RoomID, (DateTime)model.RoomTime) !=
                            null
                                ? dac.UpdateRoomIdAndRoomTime(model)
                                : dac.Add(model);
                    }
                    if (lsRecord > 0)
                    {
                       FunHelper.Alert("保存成功");
                    }
                    else
                    {
                        FunHelper.Alert("保存失败");
                    }
                }
            }
            catch (Exception)
            {
                FunHelper.Alert("保存失败!");
            }
            GetSeach();
        }
    }
}